///////////////////////////////////////////////////////////////////////
// File:        ImageFileSink.cpp
// Description: 
// Author:      Philip Kommnick
// Created:     Fri September 11 12:14:12 CEST 2009
//
// This program is open source. For license terms, see the LICENSE file.
//
///////////////////////////////////////////////////////////////////////

#include "StdAfx.h"
#include "ImageFileSink.h"

// L"Portable Network Graphics (.png)\0*.png\0Tagged Image File Format (.tiff)\0*.tiff;*.tif\0Windows Bitmap (.bmp)\0*bmp\0\0"
ImageFileSink::ImageFileSink(void)
{
	TypesList tl;
	tl.push_back(MAKEFTYPE(L"Portable Network Graphics", L"*.png"));
	tl.push_back(MAKEFTYPE(L"Tagged Image File Format", L"*.tif;*.tiff"));
	tl.push_back(MAKEFTYPE(L"Windows Bitmap", L"*.bmp"));
	InitFileDlg(tl);
}

void ImageFileSink::Output(Gdiplus::Bitmap &img)
{
	if (!RequestFileName(L"Save to image file..."))
		return; // user pressed cancel - do nothing
	CLSID *encoderClsid = NULL;
    UINT  num = 0;  // number of image encoders
    UINT  size = 0; // size of the image encoder array in bytes
    Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL;
    Gdiplus::GetImageEncodersSize(&num, &size);
    if (size == 0)
        throw std::exception("no image encoders available");  // Failure
    pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));
    if (pImageCodecInfo == NULL)
        throw std::exception("unable to read image encoders");  // Failure
    GetImageEncoders(num, size, pImageCodecInfo);
    for (UINT j = 0; j < num; ++j) {
        if ( wcscmp(pImageCodecInfo[j].MimeType, (L"image/" + GetFileExt()).c_str()) == 0 ) {
            encoderClsid = &(pImageCodecInfo[j].Clsid);
            break;  // Success
        }
    }
	if (encoderClsid)
		Gdiplus::Status stat = img.Save(GetFileName().c_str(), encoderClsid);
    free(pImageCodecInfo);
	if (!encoderClsid)
		throw std::exception("unknown file format"); // Failure
}